package com.system.config;



import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

// 连接类
public class Jdbc {
    // 数据库连接类
    private static final Properties PROPERTIES = new Properties();
    private final Connection conn;
    private final Statement stmt;

    static {
        try (InputStream input = Jdbc.class.getClassLoader().getResourceAsStream("db.properties")) {
            if (input == null) {
                throw new RuntimeException("Failed to find db.properties in resources directory.");
            }
            PROPERTIES.load(input);
        } catch (IOException e) {
            throw new RuntimeException("Failed to load db.properties: " + e.getMessage(), e);
        }
    }

    public Jdbc() {
        try {
            // 加载驱动
            Class.forName(PROPERTIES.getProperty("db.class"));

            // 建立连接
            conn = DriverManager.getConnection(
                    PROPERTIES.getProperty("db.url"),
                    PROPERTIES.getProperty("db.username"),
                    PROPERTIES.getProperty("db.password")
            );

            // 创建 Statement 对象
            stmt = conn.createStatement();
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("JDBC Driver class not found: " + e.getMessage(), e);
        } catch (SQLException e) {
            throw new RuntimeException("Failed to connect to the database: " + e.getMessage(), e);
        }
    }

    public Statement getStmt() {
        return stmt;
    }

    public PreparedStatement prepareStatement(String sql) throws SQLException {
        if (conn == null) {
            throw new SQLException("Connection is not initialized.");
        }
        return conn.prepareStatement(sql);
    }

    public void close() {
        try {
            if (stmt != null && !stmt.isClosed()) {
                stmt.close();
            }
            if (conn != null && !conn.isClosed()) {
                conn.close();
            }
        } catch (SQLException e) {
            System.err.println("Failed to close database resources: " + e.getMessage());
        }
    }
}
